from tkinter import *
# 导入ttk
from tkinter import ttk
# 导入filedialog
from tkinter import filedialog
from tkinter.messagebox import *
from tkinter import *
import requests
import re
import pyttsx3
import _thread
import json


class App:

    def __init__(self, root):
        self.root = root
        self.read = 1
        # self.book_index = 2
        self.book_names = []
        # self.is_open_type = False  # False表示当前未开启，True表示当前开启
        self.encoding_format_list = ["utf-8", "gbk"]
        self.encoding_format = "utf-8"
        self.read_file()
        self.initWidgets()


    def read_file(self):
        with open("book.json", "r", encoding= "utf-8") as f:
            self.book = json.load(f)
            self.book_index = self.book["default"]
            # self.book["books"]
            for x in self.book["books"]:
                self.book_names.append(x["name"])
            print(self.book_names)

    def write_file(self):
        with open("book.json", "w", encoding='utf-8') as f:
            json.dump(self.book, f, indent=2, sort_keys=True, ensure_ascii=False)  # 写为多行

    def initWidgets(self):
        # print(self.book)
        # print(self.book["books"][1]["book"])

        # 创建下拉列表，设置下拉列表中的值
        self.normal_ddl = Label(self.root, text='编码')
        self.ddl = ttk.Combobox(self.root, height=1, width=10)
        self.ddl['value'] = self.encoding_format_list
        self.ddl.bind("<<ComboboxSelected>>", self.xFunc)  # #给下拉菜单绑定事件

        self.get_label1 = Label(self.root, text='书名')
        self.get_text1 = Text(self.root, height=1, width=10)
        self.get_page = Button(self.root, text='上次历史', command=self.book_change)
        #设置初始化值
        self.get_text1.insert('0.0', self.book["books"][self.book_index]["name"])

        self.get_label2 = Label(self.root, text='当前页')
        self.get_text2 = Text(self.root, height=1, width=10)
        self.get_text2.insert('0.0', self.book["books"][self.book_index]["page"])

        self.button_get = Button(self.root, text='开始', command=self.text_get)
        self.button_get2 = Button(self.root, text='结束', command=self.text_get2)
        self.button_new_add = Button(self.root, text='新增', command=self.add_new_fiction)

        self.normal_ddl.grid(row=0, column=0)
        self.ddl.grid(row=0, column=1, columnspan=2)

        self.get_label1.grid(row=1, column=0)
        self.get_text1.grid(row=1, column=1, columnspan=2)
        self.get_page.grid(row=1, column=3)

        self.get_label2.grid(row=2, column=0)
        self.get_text2.grid(row=2, column=1, columnspan=2)

        self.button_get.grid(row=3, column=0)
        self.button_get2.grid(row=3, column=1)
        self.button_new_add.grid(row=3, column=2)

    def book_change(self):
        book_name = str(self.get_text1.get('0.0', END)).replace("\n", "")
        print(book_name)
        self.get_text2.delete('0.0', END)
        self.get_text2.insert('0.0', 0)
        for x in self.book["books"]:
            if book_name == x["name"]:
                self.get_text2.delete('0.0', END)
                self.get_text2.insert('0.0', x["page"])

    def text_get(self):
        self.read = 1
        book_name = str(self.get_text1.get('0.0', END)).replace("\n", "")
        index_t = 0
        for x in self.book["books"]:
            if book_name == x["name"]:
                self.book_index = index_t
            index_t = index_t + 1
        print("===========start read :" + book_name + "============")
        _thread.start_new_thread(self.get_msg, ())

    def text_get2(self):
        self.read = 0
        print("===========stop read============")

    def add_new_fiction(self):
        book = str(self.get_text1.get('0.0', END)).replace("\n", "")
        page = int(str(self.get_text2.get('0.0', END)).replace("\n", ""))
        t_data = {
            "name": book,
            "page": page
        }
        self.book["books"].append(t_data)
        self.write_file()
        print("===========添加新书" + t_data.__str__() + "============")

    def get_msg(self):
        while self.read:
            book = self.book["base_url"] + str(self.get_text1.get('0.0', END)).replace("\n", "") + ".txt"
            page = int(str(self.get_text2.get('0.0', END)).replace("\n", ""))
            # gbk
            # 黑色神幻 UTF-8
            f = open(book, encoding=self.encoding_format)
            lines = f.readlines()
            self.say(lines[page])

            self.get_text2.delete('0.0', END)
            self.get_text2.insert('0.0', page + 1)
            self.book["books"][self.book_index]["page"] = page + 1
            self.write_file()

    def say(self, str):
        engine = pyttsx3.init()
        engine.setProperty('rate', 400)
        engine.say(str)
        engine.runAndWait()

    def xFunc(self, value):
        print("----")
        print(self.ddl.get())
        self.encoding_format = self.ddl.get()


root = Tk()
root.title('-')
root.geometry("200x110")
App(root)

root.mainloop()
